#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "stu.h"

// 添加学生
int add(cls *cls_all)
{
    if (cls_all->is_load == 0) {
        load(cls_all);
    }

    if (cls_all->num > CLS_NUM) {
        printf("班级人数已满.\n");
        return -1;
    }

    cls_mate *tmp = (cls_mate *)malloc(sizeof(cls_mate));
    

    if (NULL == tmp) {
        printf("malloc error");
        return -3;
    }

    printf("姓名: ");
    scanf("%s", tmp->name);
    getchar();

    printf("性别(w/m): ");
    scanf("%c", &tmp->sex);
    getchar();

    printf("年龄： ");
    scanf("%d", &tmp->age);
    getchar();

    printf("分数： ");
    scanf("%f", &tmp->score);
    getchar();

    cls_all->stu[cls_all->num] = *tmp;
    cls_all->num++;

    int fd = open("stu.db", O_RDWR, 0664);

    if (-1 == fd) {
        printf("db 文件打开失败.");
        goto endup;
    }

    lseek(fd, 0, SEEK_END);

    if ( write(fd, tmp, sizeof(cls_mate)) == -1 ) {
        printf("写入文件失败.\n");
        goto endup;
    }

// 内存回收处理
endup:
    free(tmp);
    tmp = NULL;

    if (close(fd) == -1) {
        printf("db 文件关闭失败.\n");
    }

    return 0;
}


void list(cls *cls_all)
{
    if (cls_all->is_load == 0) {
        load(cls_all);
    }

    printf("%s\t%s\t%s\t%s\n", "姓名", "性别", "年龄", "分数");

    printf("num:%d\n", cls_all->num);

    for (int i = 0; i < cls_all->num; i++) {
        printf("%s\t%c\t%d\t%.2f\n", 
                cls_all->stu[i].name,
                cls_all->stu[i].sex,
                cls_all->stu[i].age,
                cls_all->stu[i].score
                );
    }
}


// 将文件中存储的结构体读入内存
int load(cls *cls_all)
{
    int fd = open("stu.db", O_RDWR|O_CREAT, 0664);
    ssize_t ret = -1;

    if (fd == -1) {
        printf("db 文件打开失败.\n");
        return -1;
    }

    do {
        ret = read(fd, &cls_all->stu[cls_all->num], sizeof(cls_mate));
        if (ret == -1) {
            printf("db 文件读取失败.\n");
            return -2;
        }

        if (cls_all->num > CLS_NUM) {
            printf("文件超过读取限度.\n");
            return -4;
        }

        if (ret > 0) {
            cls_all->num++;
        }
    }while (ret);

    cls_all->is_load = 1;

    if (close(fd) == -1) {
        printf("db 文件关闭失败.\n");
    }

    return 0;
}

